
# ---------------------------异常处理方案一----------------------
# try:
#     print("可能出现异常的代码")
#     print(name)
# except (NameError, ZeroDivisionError) as error_domin:
#     print('捕捉异常类型-NameError',error_domin)
#
# except ValueError as renson:
#     print("捕捉异常类型-ValueError",renson)
#
# except Exception as renson:
#     print("捕捉异常类型-Exception", renson)
#
# else:
#     print("没有异常执行代码")
# finally:
#     print("不管有没有异常都要执行的代码")


# ---------------------------异常处理方案二----------------------
# with 预处理A  处理完成之后执行清理操作
# with context[as  **arg]: 1、 __enter__ 方法进入  2、执行与具体body  3、__exit__方法退出
#    with.body

# try:
#     f = open("xxx", 'rb')
#     f.readlines()
#
# except Exception as error_domin:
#     print(error_domin)
#
# finally:
#     print("执行关闭文件")
#     f.close()
#
# with open("xx","rb") as f:
#     f.readlines()

# ---------------------------自定义上下文管理器：实现enter和exit方法----------------------

# import traceback
# class custom_context(object):
#     def __enter__(self):
#         print("enter")
#         return self
#
#     # 退出时候参数都是异常信息 和 追踪信息 如果返回true 异常不会传出去  返回false 异常会传出去
#     # 这里可以把异常写入日志
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print(self, exc_type, exc_val, exc_tb)
#         print("exit")
#         print(traceback.extract_tb(exc_tb))
#         return True
#
#
# # context 是 __enter__ 返回的对象
# with custom_context() as context:
#     print("主体代码", context)


# ---------------------------上下文模块 contextlib----------------------

import contextlib

# 生成器编程上下文管理器
# @contextlib.contextmanager
# def test():
#     print(1)
#     yield  "xxxx"
#     print(2)
#
# with test() as  s:
#     print(3, s)


# class Test(object):
#     def eat(self):
#         print("调用吃方法")
#
#     def close(self):
#         print("资源释放")
#
# with contextlib.closing(Test()) as t_object:
#     t_object.eat()


# with open("xx","rb") as  from_file:
#     with open("xx_02","wb") as  to_file:
#         from_content = from_file.read()
#         to_file.write(from_content)


# with open("xx","rb") as  from_file, open("xx_02","wb") as  to_file:
#         from_content = from_file.read()
#         to_file.write(from_content)


# ---------------------------手动抛出异常----------------------

# def set_age(age):
#     if age <= 0 or age > 100:
#         raise ValueError("设置年龄不对")  # 手动抛出异常
#     else:
#         print("设置张三的年龄是", age)
#
# set_age(18)
# set_age(-18)

# ---------------------------自定义异常----------------------

class CustomException(Exception):

    def __init__(self, message, error_code):
        self.message = message
        self.errorCode = error_code

    def __str__(self):
        return "自定义异常类的信息:{} 错误码：{}".format(self.message, self.errorCode)


def set_age(age):
    if age <= 0 or age > 100:
        raise CustomException("设置年龄不对", 404)
    else:
        print("设置张三的年龄是", age)

try:
    set_age(-18)
except Exception as e:
    print(e)


